import React, { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { ModalForm, PageContainer, ProFormText, ProTable, ProFormUploadButton } from '@ant-design/pro-components';
import { Button, message, Image, Popconfirm, Spin } from 'antd';
import errorImage from '@/assets/error.png';
import utils from '@/assets/utils';
import HOME_API from '@/services/home';
import BASE_API from '@/services/base';
import styled from 'styled-components';
const StyledFormUpload = styled.div`
    position: relative;
    .ant-form-item {
        height: 110px;
    }
    .loading{
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 1px;
        left: 94px;
        width: 102px;
        height: 102px;
        border: 1px dashed #d9d9d9;
        border-radius: 8px;
        background-color: rgba(0, 0, 0, 0.02);
    }
`;

const Banner = function Banner() {
    /* 定义表格列 */
    const columns = [{
        title: '轮播图',
        dataIndex: 'carouselUrl',
        with: '20%',
        render: (dom) => {
            return <Image
                width={60}
                height={60}
                src={dom}
                fallback={errorImage}
            />;
        }
    }, {
        title: "跳转连接",
        dataIndex: 'redirectUrl',
        width: '20%',
        render: (dom) => {
            return <Button type="link"
                style={{ padding: 0 }}
                onClick={() => window.open(dom)}>
                {dom}
            </Button>;
        }
    }, {
        title: '排序值',
        dataIndex: 'carouselRank',
        with: '10%',
    }, {
        title: '创建时间',
        dataIndex: 'createTime',
        with: '20%',
        render: (dom) => {
            if (!dom) return '--';
            return utils.formatTime(dom, '{0}-{1}-{2}');
        }
    }, {
        title: '操作',
        render: (_, record) => {
            let { carouselId, carouselUrl, carouselRank, redirectUrl } = record;
            return [
                <Popconfirm key="delete" title="确定要删除这条记录吗？" onConfirm={() => { }}>
                    <a href="#">删除</a>
                </Popconfirm>,
                <Button key="update" type="link"
                    onClick={() => {
                        // 为了防止第一次就是点击修改让Model层渲染显示，如果异步操作，下面是无法获取Model的实例的！！
                        flushSync(() => {
                            setModelVisible(true);
                            setCarouselId(carouselId);
                        });
                        // 给Model层中的各个表单赋值
                        modelFormIns.current.setFields(
                            [{
                                name: 'carouselUrl',
                                value: carouselUrl
                            }, {
                                name: 'carouselRank',
                                value: carouselRank
                            }, {
                                name: 'redirectUrl',
                                value: redirectUrl
                            }]
                        );
                        // 修改上传的文件列表
                        setFileList([{
                            url: carouselUrl
                        }]);
                    }}>
                    修改
                </Button>
            ];
        }
    }];

    /* 定义状态 */
    const [modelVisible, setModelVisible] = useState(false),
        [carouselId, setCarouselId] = useState(null),
        [fileList, setFileList] = useState([]),
        [loading, setLoading] = useState(false),
        modelFormIns = useRef();

    /* Model关闭处理 */
    const modelOpenChange = (bool) => {
        if (bool) return;
        // 即将关闭Model层
        setModelVisible(false);
        setCarouselId(null);
        setFileList([]);
        modelFormIns.current.resetFields();
    };

    /* 表格数据的处理 */
    const queryTableData = async ({ pageSize, current }) => {
        let tableData = [],
            total = 0;
        try {
            let { resultCode, data } = await HOME_API.carouselsList(current, pageSize);
            if (+resultCode === 200) {
                total = +data.totalCount;
                tableData = data.list;
            }
        } catch (_) { }
        // 不论请求成功还是失败，都让表格进行渲染
        return {
            success: true,
            data: tableData,
            total
        };
    };

    /* 关于文件上传 */
    const onBeforeUpload = (file) => {
        // 限制文件上传的大小
        if (file.size > 1024 * 1024) {
            message.warning('上传的图片需要小于1MB');
            return false;
        }
        return true;
    };
    const onUploadChange = async ({ file }) => {
        setLoading(true);
        try {
            let { resultCode, data } = await BASE_API.uploadFile(file);
            if (+resultCode !== 200) {
                message.error('上传失败，请稍后重试~');
                setLoading(false);
                return;
            }
            // 上传成功后：修改文件列表、设置Form收集的信息
            setFileList([{
                url: data
            }]);
            modelFormIns.current.setFieldValue('carouselUrl', data);
        } catch (_) { }
        setLoading(false);
    };

    return <PageContainer>
        {/* 表格区域 */}
        <ProTable
            request={queryTableData}
            columns={columns}
            rowKey="carouselId"
            search={false}
            toolBarRender={() => {
                return [
                    <Button key="new" type="primary"
                        onClick={() => setModelVisible(true)}>
                        <PlusOutlined /> 新增
                    </Button>,
                    <Button key="delete" type="primary" danger
                        onClick={() => { }}>
                        <MinusOutlined /> 批量删除
                    </Button>
                ];
            }}
            options={{
                density: false,
                reload: true,
                setting: true
            }}
            pagination={{
                pageSize: 10,
                hideOnSinglePage: false,
                showTotal: false,
                showQuickJumper: false,
                showSizeChanger: false
            }}
            rowSelection={{
                onChange: (selectedIds, selectedRows) => { }
            }}
        />

        {/* 弹出框 */}
        <ModalForm
            title={`${carouselId ? '修改' : '新增'}轮播图信息`}
            width="500px"
            layout='horizontal'
            open={modelVisible}
            onOpenChange={modelOpenChange}
            formRef={modelFormIns}
            labelCol={{ span: 5 }}
            validateTrigger="onBlur"
            initialValues={{
                carouselUrl: '',
                carouselRank: '',
                redirectUrl: ''
            }}
            onFinish={async (value) => { }}
        >
            <StyledFormUpload>
                <ProFormUploadButton
                    name="carouselUrl"
                    label="上传图片"
                    rules={[
                        { required: true, message: '请您先上传图片' }
                    ]}
                    max={1}
                    fieldProps={{
                        fileList,
                        customRequest: onUploadChange,
                        accept: 'image/*',
                        listType: 'picture-card',
                        beforeUpload: onBeforeUpload,
                        onRemove: () => {
                            setFileList([]);
                            modelFormIns.current.setFieldValue('carouselUrl', '');
                        }
                    }}
                />
                <div className="loading"
                    style={{
                        display: loading ? 'flex' : 'none'
                    }}>
                    <Spin />
                </div>
            </StyledFormUpload>

            <ProFormText
                label="排序值"
                name="carouselRank"
                placeholder="范围1~200之间"
                rules={[
                    {
                        required: true,
                        validator: (_, value) => {
                            if (isNaN(value)) return Promise.reject('请输入有效数字');
                            if (value < 1 || value > 200) return Promise.reject('输入的值必须在1~200之间');
                            return Promise.resolve();
                        }
                    }
                ]}
            />
            <ProFormText
                label="跳转连接"
                name="redirectUrl"
                placeholder="请输入正确的网址"
                rules={[
                    { required: true, message: '请输入跳转连接' },
                    { pattern: /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/, message: '请输入正确的网址' }
                ]}
            />
        </ModalForm>
    </PageContainer>;
};
export default Banner;